//
//  PhotoViewerCellCollectionViewController.swift
//  CLWeiBo
//
//  Created by 程雷 on 15/7/3.
//  Copyright © 2015年 程雷. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

protocol PhotoViewCellDelegate:NSObjectProtocol{
    func photoViewCellDidTapImage()
    ///  照片视图正在缩放
    func photoViewDidZooming(scale:CGFloat)
    /// 照片视图完成缩放
    func photoViewerDidEndZoom()
}
class PhotoViewerCell: UICollectionViewCell,UIScrollViewDelegate {

    weak var photoDelegate:PhotoViewCellDelegate?
    var imageURL:NSURL?{
        didSet{
            
            // 重设 scrollerView 内容参数
            resetScrollerView()
            //显示菊花
            indicator.startAnimating()
            
            imageView.sd_setImageWithURL(imageURL!, placeholderImage: nil) { (image, error, _, _) in
                // 隐藏菊花
                self.indicator.stopAnimating()
                //下载完成之后 自动设置图像尺寸
                self.imagePosition(image)
            }
        }
    }
    
    // scrollerView 内容参数
    private func resetScrollerView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    //MARK ---UIScrollViewDelegate
    // 告诉 ScrollView 缩放谁
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    // 缩放结束，会执行一次
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        // 如果 scale <0.8 直接解除缩放
        if scale>0.8
        {
            //重新计算边距
            var offsetX = (scrollView.bounds.width-view!.frame.width)*0.5
            if offsetX < 0
            {
                offsetX = 0
            }
            var offsetY = (scrollView.bounds.height-view!.frame.height)*0.5
            if offsetY < 0
            {
                offsetY = 0
            }
            // 重新设置边距
            scrollView.contentInset = UIEdgeInsets(top: offsetX, left: offsetY, bottom: 0, right: 0)
        }
        
        // 通知代理完成缩放
        photoDelegate?.photoViewerDidEndZoom()
    }
    ///  该方法会频繁调用
    ///
    ///  :param: scrollView <#scrollView description#>
    /**
    var a: CGFloat  缩放
    var b: CGFloat
    var c: CGFloat
    var d: CGFloat  缩放
    var tx: CGFloat  位移
    var ty: CGFloat   位移
    
    a b c d 共同决定旋转
    */
    func scrollViewDidZoom(scrollView: UIScrollView) {
        let scale = imageView.transform.a
        photoDelegate?.photoViewDidZooming(scale)
    }
    private func imagePosition(image:UIImage) {
        // 计算 y 值
        let size = displaySize(image)
        // 判断是否是长图
        if bounds.height < size.height
        {
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentSize = size
        }
        else {
            // 短图
            let y = (bounds.height - size.height)*0.5
           // imageView.frame = CGRect(origin: CGPoint(x: 0, y: y), size: size)
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }
    }
    
    private func displaySize(image:UIImage) ->CGSize {
        
        let scale = image.size.height/image.size.width
        let h = scrollView.bounds.width * scale
        return CGSize(width: scrollView.bounds.width, height: h)
    }
    // 点击图片的时候调用代理
    func clickImage()
    {
        photoDelegate?.photoViewCellDidTapImage()
    }
    // frame 已经有正确的值，因为之前的 layout 已经设置过
    override init(frame:CGRect){
        
        super.init(frame: frame)
        print("cell的大小\(frame)")
        scrollView.frame = UIScreen.mainScreen().bounds
        scrollView.backgroundColor = UIColor.clearColor()
        addSubview(scrollView)
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        //设置 imageView 的手势监听
        let tap = UITapGestureRecognizer(target: self, action: "clickImage")
        imageView.addGestureRecognizer(tap)
        // 打开可交互界面
        imageView.userInteractionEnabled = true
        
        scrollView.addSubview(imageView)
        addSubview(indicator)
        indicator.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: nil)

    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK---懒加载控件
    lazy var imageView = UIImageView()
    lazy private var scrollView = UIScrollView()
    
    // 小菊花
    lazy private var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    

}
